import torchvision.transforms as transforms
import torch
import cv2
import numpy as np
from PIL import Image

"""读取图片cv2"""
img = cv2.imread("./opencv/zidane.jpg")
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
print("原图",img.shape,img.dtype)  # numpy数组格式为（H,W,C）

"""图片产生矩阵"""
im = np.asarray(img,dtype="float32")
print(im.shape,im.dtype)

"""随机生成矩阵"""
im2 =  np.random.rand(3, 1368, 1487)
im3 = np.zeros((3,3),dtype="float32")
im4 = np.ones((3,3),dtype="uint8")
im5 = np.eye(3)
print("数据矩阵",im2.shape,im2.dtype)
print(im3)
print(im4)
print(im5)

"""读取图片生成张量"""
transf = transforms.ToTensor()
img_tensor = transf(img) # tensor数据格式是torch(C,H,W)
print(img_tensor.shape,img_tensor.dtype)

"""用数字随机产生多维张量"""
input = torch.rand(3, 1368, 1487)
print(input.shape,input.dtype)

"""同尺寸张量拼接"""
input1 = torch.rand(128, 52, 52)
input2 = torch.rand(256, 52, 52)
output1 = torch.cat((input1,input2),0)  # 分类任务横着拼
print(output1.shape,output1.dtype)

"""同尺寸张量拼接"""
input1 = torch.rand(4,3, 2, 2)    # class_num*len,channels,x,y
input2 = torch.rand(4,4, 2, 2)
output = torch.cat((input1,input2),dim=1)  # 目标检测任务横着拼
print(output,output.shape,output.dtype)

"""tensor转array"""
torch_data = torch.from_numpy(im2)
array2 = torch_data.numpy()
print("array转tensor",torch_data.shape,torch_data.dtype,"tensor转array",array2.shape,array2.dtype)

"""张量升/降维数"""
# view()    降维维度
# reshape() 转换维度
# permute() 坐标系变换
# squeeze()/unsqueeze()   先改每个排序 后进行降维/升维
# expand()   扩张张量
# narraw()   缩小张量
# resize_()  重设尺寸
# repeat(), unfold() 重复张量
# cat(), stack()     拼接张量
input1 = input.view(input.size(0), -1)  # 转成那么多行，不降维数
print(input1.shape,input1.dtype)

# 矩阵可以看成二维列表
print(im[1:].shape)
input2 = np.array(im[1:],dtype="float32").reshape(-1,2)  # 转成两列，不降维数
print(input2.shape)

